<template>
  <div>
    <el-card>
      <div style="display: flex; justify-content: space-between;">
        <el-statistic title="教练总数" :value="totalcoaches" />
        <el-button type='warning' @click="handleAC">添加教练</el-button>
        <el-input v-model="searchQuery" placeholder="搜索教练" style="width: 300px;" />
      </div>
    </el-card>
    <!-- 表格数据来源是后端查询的数据 -->
    <el-table :data="Coaches" style="width: 100%; margin-top: 20px;">
        <!-- prop用来获取data的键名 -->
      <el-table-column prop="eeNum" label="教练编号" />
      <el-table-column prop="eeName" label="教练姓名" />
      <el-table-column prop="eeType" label="类型">
      </el-table-column>
      <!-- <el-table-column prop="perform" label="业绩">
      </el-table-column> -->
      <el-table-column prop="eePhone" label="电话号码" />
      <el-table-column label="操作">
        <!--  -->
        <template #default="scope">
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog v-model="addcoachDialogVisible" title="添加教练">
      <!-- 编辑表单 -->
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules"
      label-width="auto">
       <el-form-item label="教练姓名" prop="coachName"> 
    <el-input v-model="ruleForm.coachName" />
  </el-form-item>
  
     <el-form-item label="类型" prop="教练">
        <el-input v-model="ruleForm.coach" disabled/>
  </el-form-item>
  
  <el-form-item label="电话号码" prop="phoneNum">
    <el-input v-model="ruleForm.phoneNum"/>
  </el-form-item>

      <el-form-item style="padding-left: 40%;">
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">
          清空
        </el-button>
      </el-form-item>
    </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive} from 'vue'
import axios from 'axios'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { errorMessages } from 'vue/compiler-sfc'


// 定义响应式数组数据coachs
const coaches = ref([])
// 搜索会员响应数据
const searchQuery = ref('')

// 总会员数量 计算数组长度
const totalcoaches = computed(() => coaches.value.length)

const getAllcoachs = (async()=>{
    // 获取coach表 /api/coachs是后端的相对地址
  const response = await axios.get('/api/employees/coaches')
  coaches.value = response.data
  console.log(coaches.value)

})

//过滤数据表 将需要的输出 
const Coaches = computed(() => {
    try{
    // 如果搜索的关键字的值为空 则返回所以 数组值
  if (!searchQuery.value) return coaches.value
// 否则返回搜索的  
  return coaches.value.filter(coach => 
//   通过课程名来过滤筛选
    coach.eeName.includes(searchQuery.value) )
    }catch(error){
        console.log(errorMessages)
    }
})

// 挂载后端请求的数据
 onMounted(()=> {
    getAllcoachs()
})

// // 删除课程
const handleDelete = async (coach) => {
  await axios.delete(`/api/employees/${coach.eeNum}`)
  coaches.value = coaches.value.filter(c => c.coachNum !== coach.coachNum)
  ElMessage.success('删除成功!')
  // 再次渲染删除后的列表
  const update = await axios.get('/api/employees/coaches')
  coaches.value = update.data

//   onMounted(() => {
//   handleDelete()
// })
}
// 页面数据
// const coachInfo = ref({
//     coachName: '',
//     coach: '会籍',
//     phoneNum: '',
// })
// 编辑框是否可见 默认不可见
const addcoachDialogVisible = ref(false)
const handleAC = async () => {
  // 课程办理对话框弹出
  addcoachDialogVisible.value= true
}

// 表单接口
interface RuleForm {
    coachName: String,
    coach: String,
    phoneNum: String,   
}

const ruleForm = reactive<RuleForm>({
    coachName: '',
    coach: '教练',
    phoneNum: '',         
})

// 更新表单规则
const rules = reactive<FormRules<RuleForm>>({
  coachName: [ 
    { required: true, message: '请输入会籍姓名', trigger: 'blur' },
    { min: 2, max: 4, message: '姓名格式有误', trigger: 'blur' },
  ],
//   coach: [  
//     { required: true, message: '请选择授课教练', trigger: 'blur' }
//   ],
  phoneNum: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { min: 11, max: 11, message: '号码格式错误', trigger: 'blur' },
  ],
})
// ruleFormRef用于引用表单实例FormInstance
const ruleFormRef = ref<FormInstance>()

// const coachOptions = ref([])

// 加载选项数据 请求后端
// const loadOptions = async () => {
//   try {
//     // 请求后端 获取响应数据
//     const coachRes = await axios.get('/api/employees/coaches')
//     console.log(coachRes)
//     // 处理健身卡选项
//     coachOptions.value = coachRes.data.map(coach => ({
//       label: coach.eeName,  // 使用 cardName 作为显示文本
//       value: coach.eeName   // 使用 cardName 作为值
//     }));
    
    // // 处理会籍选项
    // coachOptions.value = coachsRes.data.map(coach => ({
    //   label: coach.eeName,   // 使用 eeName 作为显示文本
    //   value: coach.eeName    // 使用 eeName 作为值
    // }));
    
//   } catch (error) {
//     console.error('加载选项失败:', error);
//     ElMessage.error('加载选项失败，请稍后重试');
//   }
// }
// 挂载
// onMounted(() => {
//   loadOptions()
// })


const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
        try{
        // 创建符合后端要求的数据结构
        const coachData = {
          eeName: ruleForm.coachName,
          eeType: ruleForm.coach,
          eePhone: ruleForm.phoneNum
        }
        
        await axios.post('/api/employees', coachData)
        console.log('办理成功!')
        ElMessage.success('添加成功!')
        formEl.resetFields()
      }catch(error){
        console.log(errorMessages)
    }
    const update = await axios.get('/api/employees/coaches')
  coaches.value = update.data
}
  })

}

// 重置表单函数
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // formEl.resetFields()：Element Plus 提供的表单重置方法
  formEl.resetFields()
}

</script>